package cn.christ.com.mobilesafe.common.utils.Contactsutils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;

import java.util.ArrayList;
import java.util.List;

public class ContactsUtils {
	public static final Uri RAW_CONTATS_URI = Uri.parse("content://com.android.contacts/raw_contacts");
	public static final Uri DATA_URI = Uri.parse("content://com.android.contacts/data");

	public static List<ContactInfo> queryAllContacts(Context context) {
		// 1 先要获取联系人(contact_id)id （raw_contacts）
		List<ContactInfo> contacts = new ArrayList<ContactInfo>();
		ContentResolver cr = context.getContentResolver();
		Cursor cursor = cr.query(RAW_CONTATS_URI, new String[] { "contact_id" }, null, null, null);
		if (cursor != null) {
			while (cursor.moveToNext()) {
				int contact_id = cursor.getInt(0);// 1
				// 2 通过这个contact_id 获取data表里面，data1和mimetype
				Cursor cursor2 = cr.query(DATA_URI, new String[] { "data1", "mimetype" }, "raw_contact_id=?",
						new String[] { String.valueOf(contact_id) }, null);
				ContactInfo contact = new ContactInfo();
				contacts.add(contact);
				contact.contactId = contact_id;
				if (cursor2 != null) {
					while (cursor2.moveToNext()) {
						String data1 = cursor2.getString(0);
						String mimeType = cursor2.getString(1);
						// 3 data1：可能是电话号码也可能是名字，通过mimetype区分是到底是电话号码还是名字
						if ("vnd.android.cursor.item/phone_v2".equals(mimeType)) {
							contact.phone = data1;
						} else if ("vnd.android.cursor.item/name".equals(mimeType)) {
							contact.name = data1;
						}

					}
					cursor2.close();
				}

			}
			cursor.close();
		}
		return contacts;
	}

	// 根据联系人的id查询图片（Bitmap）
	public static Bitmap getBitmapFromContactId(Context context, int contactId) {
		// 1 获取内容解析这
		ContentResolver cr = context.getContentResolver();
		// 2 获取Cursor
		Cursor cursor = cr.query(DATA_URI, new String[] { "data15", "mimetype" }, "raw_contact_id=?",
				new String[] { String.valueOf(contactId) }, null);
		if(cursor!=null){
			while(cursor.moveToNext()){
				// 获取图片的数组
				byte[] bytes = cursor.getBlob(0);
				String mimetype=cursor.getString(1);
				if("vnd.android.cursor.item/photo".equals(mimetype)){
					// 确保是图片
					if(bytes!=null){
						Bitmap bitmap=BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
						cursor.close();
						return bitmap;
					}
				}
				
			}
		}
		return null;
	}
}
